package com.zy.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.config.WhiteUrlsConfig;
import com.zy.constant.AuthConstants;
import com.zy.constant.BusinessEnum;
import com.zy.constant.HttpConstants;
import com.zy.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 全局 token过滤器
 * 约定好的token存放位置：请求头的 Authorization bearer token
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * 校验token
         * 1.获取请求路径
         * 2.判断请求路径是否可以放行
         *  放行：不需要认证身份
         *  不放行：进行身份认证
         */
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getPath().toString();
        //验证当前路径是否在请求路径白名单中(登录路径)
        if (whiteUrlsConfig.getAllowUrls().contains(path)) {
            //白名单，放行
            return chain.filter(exchange);
        }

        //非白名单，需要身份认证
        //在约定位置获取Authorization的值，值的格式为 Authorization="bearer " + token
        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        //判断authorization是否有值
        if(StringUtils.hasText(authorization)){
            //获取token，去掉前缀 "bearer "
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            //判断token是否有值且是否存在Redis中
            if(StringUtils.hasText(token) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + token)){
                //身份认证通过，放行
                return chain.filter(exchange);
            }
        }
        //执行到此，说明身份认证不通过或请求不合法，响应错误信息
        log.error("拦截非法请求，时间:{}, 请求API路径:{}", new Date(), path);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头信息
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);
        //设置响应信息，没有token 即401无身份认证
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);

        //创建一个ObjectMapper对象，可以将java对象转换成json字符串、byte数组等
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            //将result转为byte数组
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 优先级，越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return -5;
    }
}
